import json
import logging
from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest


class Aliyun:
    def __init__(self):
        # 阿里云登陆信息
        self.AccessKey_ID = ''
        self.AccessKey_Secret = ''
        self.Region_Id = 'cn-hangzhou'
        # 阿里云ecs列表接口参数
        self.request = DescribeInstancesRequest()
        self.request.set_accept_format('json')  # 返回的数据格式
        self.request.set_VpcId("")  # 机器所在vpc id
        self.request.set_SecurityGroupId("")  # 机器所属安全组id
        self.request.set_PageSize(100)  # 最大机器个数
        self.request.set_Status("Running")  # 机器状态

    def get_instances(self):
        """
        获取阿里云机器信息
        :return: {ip: hostname}
        """
        client = AcsClient(self.AccessKey_ID, self.AccessKey_Secret, self.Region_Id)
        response = json.loads(client.do_action_with_exception(self.request))
        instance_dict = {}
        try:
            instance_list = response.get('Instances').get('Instance') if response else []
            for instance in instance_list:
                instance_dict[instance['VpcAttributes']['PrivateIpAddress']['IpAddress'][0]] = instance[
                        'InstanceName']
            return instance_dict
        except Exception as e:
            logging.error(e)
